import axios from 'axios'
import { useStorage } from "@vueuse/core";
import { useUserStore } from '@/store';
import { ElMessage, ElMessageBox } from "element-plus";

const service = axios.create({
  baseURL: '/api'
})

service.interceptors.request.use(config => {
  config.headers.reqId = Date.now()
  const token = useStorage("token", null)
  if (token) {
    config.headers.Token = `${token.value}`
  }
  return config
}, error => {
  console.log('错误信息', error)
  return Promise.reject(error);
})

service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.config.responseType === 'arraybuffer' || response.config.responseType === 'blob') return response.data;
    if (res.code != 200) {
      ElMessage({
        message: res.message || "Error",
        type: "error"
      });
      if ([401].includes(res.code) && response.config.url !== '/api/user/info') {
        ElMessageBox.confirm(
          "你已被登出，可以取消继续留在该页面，或者重新登录",
          "登录过期",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          const userStore = useUserStore();
          userStore.logout();
        }).catch(() => {});
      }
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  }, (error) => {
    ElMessage({
      message: error.message || "Request Error",
      type: "error",
      grouping: true,
    });
    return Promise.reject(error);
  }
)

export default service